package com.czq.gulimail.gulimailproduct.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czq.common.to.MemberPriceTo;
import com.czq.common.to.SkuFullReductionTo;
import com.czq.common.to.SkuLadderTo;
import com.czq.common.to.SpuBoundTo;
import com.czq.common.utils.PageUtils;
import com.czq.common.utils.Query;
import com.czq.gulimail.gulimailproduct.dao.SpuInfoDao;
import com.czq.gulimail.gulimailproduct.entity.*;
import com.czq.gulimail.gulimailproduct.feign.CouponFeignService;
import com.czq.gulimail.gulimailproduct.service.SpuInfoDescService;
import com.czq.gulimail.gulimailproduct.service.SpuInfoService;
import com.czq.gulimail.gulimailproduct.vo.Skus;
import com.czq.gulimail.gulimailproduct.vo.SpuSaveVO;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesServiceImpl spuImagesService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private AttrServiceImpl attrService;
    @Autowired
    private ProductAttrValueServiceImpl productAttrValueService;
    @Autowired
    private SkuImagesServiceImpl skuImagesService;
    @Autowired
    private SkuInfoServiceImpl skuInfoService;
    @Autowired
    private SkuSaleAttrValueServiceImpl skuSaleAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void spuSave(SpuSaveVO spuSaveVO) {

        //1.保存spu 基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVO, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);

        //新增完拿到spuId
        Long spuId = spuInfoEntity.getId();

        //2.保存图片描述 pms_spu_info_desc
        List<String> describes = Optional.ofNullable(spuSaveVO.getDecript())
                .orElse(Collections.emptyList());
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuId);
        spuInfoDescEntity.setDecript(String.join(",", describes));
        spuInfoDescService.save(spuInfoDescEntity);


        //3.保存spu图片信息 pms_spu_images
        List<SpuImagesEntity> spuImagesEntities = Optional.ofNullable(spuSaveVO.getImages())
                .orElse(Collections.emptyList())
                .stream()
                .map(s -> {
                    SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                    spuImagesEntity.setSpuId(spuId);
                    spuImagesEntity.setImgUrl(s);
                    return spuImagesEntity;
                })
                .toList();
        spuImagesService.saveBatch(spuImagesEntities);


        //4.保存商品积分 gulimail_sms ->sms_spu_bounds
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(spuSaveVO.getBounds(), spuBoundTo);
        spuBoundTo.setSpuId(spuId);
        couponFeignService.saveBound(spuBoundTo);


        //5.保存baseAttr  pms_product_attr_value
        List<ProductAttrValueEntity> productAttrValueEntities = Optional.ofNullable(spuSaveVO.getBaseAttrs())
                .orElse(Collections.emptyList())
                .stream()
                .map(attr -> {
                    ProductAttrValueEntity pva = new ProductAttrValueEntity();
                    AttrEntity attrEntity = attrService.getById(attr.getAttrId());
                    pva.setSpuId(spuId);
                    pva.setAttrValue(attr.getAttrValues());
                    pva.setAttrName(attrEntity.getAttrName());
                    pva.setQuickShow(attr.getShowDesc());
                    return pva;
                })
                .toList();
        productAttrValueService.saveBatch(productAttrValueEntities);


        //6. 保存sku
        if (spuSaveVO.getSkus() == null)
            return;


        for (Skus sku : spuSaveVO.getSkus()) {

            //6.1 保存sku基本信息 pms_sku_info
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            skuInfoEntity.setSpuId(spuId);
            BeanUtils.copyProperties(sku, skuInfoEntity);
            skuInfoEntity.setBrandId(spuSaveVO.getBrandId());
            skuInfoEntity.setCatalogId(spuSaveVO.getCatalogId());
            skuInfoEntity.setSaleCount(0L);


            //6.2 保存sku图片信息 pms_sku_images
            List<SkuImagesEntity> skuImagesEntities = Optional.ofNullable(sku.getImages())
                    .orElse(Collections.emptyList())
                    .stream()
                    .filter(entity-> !StringUtils.isNullOrEmpty(entity.getImgUrl()))
                    .map(image -> {
                        if(image.getDefaultImg() == 1)
                            skuInfoEntity.setSkuDefaultImg(image.getImgUrl());
                        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                        BeanUtils.copyProperties(image, skuImagesEntity);
                        return skuImagesEntity;
                    })
                    .toList();

            skuInfoService.save(skuInfoEntity);

            skuImagesEntities.forEach(skuImagesEntity -> {
                skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
            });
            skuImagesService.saveBatch(skuImagesEntities);


            //6.3 保存sku销售属性 pms_sku_sale_attr_value
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = Optional.ofNullable(sku.getAttr())
                    .orElse(Collections.emptyList())
                    .stream()
                    .map(attr -> {
                        SkuSaleAttrValueEntity saleAttrValueEntity = new SkuSaleAttrValueEntity();
                        BeanUtils.copyProperties(attr, saleAttrValueEntity);
                        saleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                        return saleAttrValueEntity;
                    })
                    .toList();
            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);


            //6.4 sku 优惠 满减信息 gulimail_sms -> sms_sku_ladder   sm_sku_full_reduction  sms_member_price
            SkuLadderTo skuLadderTo = new SkuLadderTo();
            BeanUtils.copyProperties(sku, skuLadderTo);
            skuLadderTo.setSkuId(skuInfoEntity.getSkuId());
            skuLadderTo.setPrice(sku.getPrice().multiply(sku.getDiscount()));
            skuLadderTo.setAddOther(sku.getCountStatus());
            if( skuLadderTo.getDiscount().compareTo(new BigDecimal("1"))<0 && skuLadderTo.getDiscount().compareTo(new BigDecimal("0"))>0)
                couponFeignService.saveSkuLadder(skuLadderTo);

            // sm_sku_full_reduction
            SkuFullReductionTo skuFullReductionTo = new SkuFullReductionTo();
            BeanUtils.copyProperties(sku, skuFullReductionTo);
            skuFullReductionTo.setSkuId(skuInfoEntity.getSkuId());
            skuFullReductionTo.setAddOther(sku.getPriceStatus());
            if(skuFullReductionTo.getReducePrice().compareTo(BigDecimal.ZERO)>0)
                couponFeignService.saveSkuReductionTo(skuFullReductionTo);

            //sms_member_price
            List<MemberPriceTo> memberPriceTos = Optional.ofNullable(sku.getMemberPrice())
                    .orElse(Collections.emptyList())
                    .stream()
                    .map(memberPrice -> {
                        MemberPriceTo memberPriceTo = new MemberPriceTo();
                        memberPriceTo.setSkuId(skuInfoEntity.getSkuId());
                        memberPriceTo.setMemberPrice(memberPrice.getPrice());
                        memberPriceTo.setMemberLevelId(memberPrice.getId());
                        memberPriceTo.setMemberLevelName(memberPrice.getName());
                        return memberPriceTo;
                    })
                    .toList();
            couponFeignService.saveMemberPriceTo(memberPriceTos);

        }



    }

}
